	<template>
		<view class="content">
			<!-- <z-paging ref="paging" v-model="dataList" @query="queryList"> -->
			<scroll-view class="content" @scrolltolower="scrolltolower" scroll-y lower-threshold="200" :scroll-into-view="scrollToId">
				<view v-for="(item,index) in grouplist" :key="index" class="groupView" ref="groupViews"
					v-if="actionIndex == -1 || actionIndex>=index" :id="'group'+item.group_id">
					<view class="groupTop"
						style="height: 80rpx;display: flex;align-items: center;justify-content: space-between;"
						@click="openGroup(index,item)">
						<view class="groupTopLeft">
							<u-icon :custom-style="{
								width: '25rpx',
								height: '25rpx'	
							}" :name="item.isUnfold ? 'https://lanhu.oss-cn-beijing.aliyuncs.com/SketchPng6dea3b4790ef587df79d71ea2ba13a57d039df4e6bb0e527b37c1adfade281bc':'https://lanhu.oss-cn-beijing.aliyuncs.com/SketchPng433354d54af0d1981fd80c3742a2cad1f21b686b00deac13cd7a7e30e226d56c'"></u-icon>
							<text class="groupname">{{item.group_name}}</text>
						</view>
						<text class="groupvalue">{{item.count}}</text>
					</view>
					<view class="listitemview" v-if="item.isUnfold">
						<view class="listitem" v-for="(cell, idx) in item.data" :key="'item' + idx"
							@click="goFriend(cell)">
							<!-- 用户数据展示 -->
							<view class="listitem__left">
								<cl-avatar :src="cell.avatar_url" size="100rpx"></cl-avatar>
							</view>
							<view class="listitem__right">
								<view class="listitem__right__top">
									<text
										class="listitem__right__top__nickname">{{cell.friend_remark || cell.nick_name}}</text>
									<text
										v-if="cell.user_type && cell.user_type > 0 && cell.user_type != 6 && cell.user_type != 8"
										class="typetag"
										style="background-color: #02D478;">{{$t('common.friend.authority')}}</text>
								</view>
								<view class="listitem__right__content">
									<text v-if="friendOnline[cell.friend_idx]"
										style="color: #6aaf76;font-size: 24rpx;">[{{$t("common.friend.online")}}]</text>
									<text v-else
										style="color: #595A66;font-size: 24rpx;">[{{$t("common.friend.offline")}}]</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
			<!-- </z-paging> -->
		</view>
	</template>

	<script>
		function throttle(func, delay) {
			let lastCall = 0;
			return function(...args) {
				const now = new Date().getTime();
				if (now - lastCall < delay) return;
				lastCall = now;
				return func(...args);
			};
		}
		import friendGroupApi from "@/services/api/friendsGroup.js"
		import {
			mapState
		} from 'vuex'
		export default {
			name: 'friend_group',
			data() {
				return {
					grouplist: [],
					// 当前组件是否已经加载过了
					firstLoaded: false,
					// 是否滚动到当前页
					isCurrentPage: false,
					pageSize: 15, // 每页加载的数据条数
					loading: false, // 全局加载状态
					actionIndex: -1,
					scrollToId:'',
				}
			},
			props: {
				// 当前组件的index，也就是当前组件是swiper中的第几个
				tabIndex: {
					type: Number,
					default: function() {
						return 0
					}
				},
				// 当前swiper切换到第几个index
				currentIndex: {
					type: Number,
					default: function() {
						return 0
					}
				},
				searchval: {
					type: String,
					default: function() {
						return ''
					}
				},
			},
			computed: {
				...mapState({
					friendList: state => state.friends.friendList,
					friendOnline: state => state.friends.friendOnline,
				}),
				// friendGroupList(){
				// 	//这里是现在离线排序，要求的时候再打开
				// 	let friendData = JSON.parse(JSON.stringify(this.friendList))
				// 	friendData.sort((friend1, friend2) => {
				// 		  const isFriend1Online = this.friendOnline[friend1.friend_idx] || false; // 判断friend1是否在线
				// 		  const isFriend2Online = this.friendOnline[friend2.friend_idx] || false; // 判断friend2是否在线

				// 		  // 如果friend1在线而friend2不在线，将friend1排在前面
				// 		  if (isFriend1Online && !isFriend2Online) {
				// 			return -1;
				// 		  }
				// 		  // 如果friend2在线而friend1不在线，将friend2排在前面
				// 		  if (!isFriend1Online && isFriend2Online) {
				// 			return 1;
				// 		  }
				// 		  // 否则保持原来的顺序
				// 		  return 0;
				// 	});
				// 	let newdata = JSON.parse(JSON.stringify(this.grouplist))
				// 	console.log(newdata);
				// 	for (let index in newdata) {
				// 		let data = newdata[index]
				// 		if(data.group_id == 0){
				// 			newdata[index].data = friendData.filter(item=>{
				// 				if(this.searchval && item.friend_remark.indexOf(this.searchval) === -1 && item.nick_name.indexOf(this.searchval) === -1){
				// 					return false
				// 				}
				// 				return item.friend_group == data.group_id || !item.friend_group
				// 			})
				// 		}else{
				// 			newdata[index].data = friendData.filter(item=>{
				// 				if(this.searchval && item.friend_remark.indexOf(this.searchval) === -1 && item.nick_name.indexOf(this.searchval) === -1){
				// 					return false
				// 				}
				// 				return item.friend_group == data.group_id
				// 			})
				// 		}
				// 	}
				// 	let searchData = newdata.filter(item => {
				// 		// 根据名字筛选
				// 		if (this.searchval && !item.data.length) {
				// 			return false;
				// 		}
				// 		return true;
				// 	});
				// 	return searchData
				// }
			},
			watch: {
				currentIndex: {
					handler(newVal) {
						if (newVal === this.tabIndex) {
							// 懒加载，当滑动到当前的item时，才去加载
							if (!this.firstLoaded) {
								this.getlist()
								this.isCurrentPage = true;
							}
						}
					},
					immediate: true
				},
				friendList: {
					handler(newVal) {
						this.grouplist = resapi.list.map(group => {
							let friendData = JSON.parse(JSON.stringify(this.friendList));
							let newItemsAll = friendData.filter(item => {
								if (group.group_id === 0) {
									return !item.friend_group || item.friend_group === group.group_id;
								} else {
									return item.friend_group === group.group_id;
								}
							})
							return {
								...group,
								count: newItemsAll.length,
							}
						});
					},
					deep: true
				},
			},
			created() {
				//通知页面
				uni.$on('onFriendGroupManage', this.onFriendGroupManage)
				this.getlist()
			},
			destroyed() {
				uni.$off('onFriendGroupManage', this.onFriendGroupManage)
			},
			methods: {
				openGroup(index, item) {
					console.log(item);
					item.isUnfold = !item.isUnfold
					//设置手风琴模式，只打开一个
					if (item.isUnfold) {
						//当前活跃的窗口
						this.loadMoreData(index);
						//关闭其他的
						this.grouplist.forEach((group, idx) => {
							if (idx != index) {
								this.grouplist[idx].isUnfold = false
								this.grouplist[idx].data = []
								this.grouplist[idx].hasMore = true
								this.grouplist[idx].currentPage = 1
							}
						});
						this.$nextTick(()=>{
							this.scrollToId = 'group'+item.group_id
						})
					} else {
						this.actionIndex = -1
						item.data = []
						item.hasMore = true
						item.currentPage = 1
					}
					
					// if (item.isUnfold && item.hasMore) {
					// 	this.actionIndex = index
					// } else if (this.actionIndex == index && !item.isUnfold) {
					// 	this.grouplist.forEach((group, index) => {
					// 		if (group.isUnfold && group.hasMore) {
					// 			this.actionIndex = index
					// 			return
					// 		}
					// 	});
					// 	this.actionIndex = -1
					// }
				},
				scrolltolower(e) {
					this.grouplist.forEach((group, index) => {
						if (group.isUnfold) {
							this.loadMoreData(index);
						}
					});
				},
				searchInput(e) {
					uni.$u.debounce(() => {
						this.searchval = e
					}, 500, false)
				},
				async getlist() {
					try {
						let resapi = await friendGroupApi.list();
						if (resapi) {
							this.grouplist = resapi.list.map(group => {
								let friendData = JSON.parse(JSON.stringify(this.friendList));
								let newItemsAll = friendData.filter(item => {
									if (group.group_id === 0) {
										return !item.friend_group || item.friend_group === group.group_id;
									} else {
										return item.friend_group === group.group_id;
									}
								})
								return {
									...group,
									currentPage: 1, //当前页
									hasMore: true, //是否有更多数据
									isUnfold: false, //是否打开当前选项
									data: [], // 初始化空数组
									count: newItemsAll.length,
								}
							});
							this.firstLoaded = true;
							// this.loadInitialData(); // 加载第一页数据
						}
					} catch (e) {
						//TODO handle the exception
					}
				},
				// loadInitialData() {
				// 	this.grouplist.forEach((group, index) => {
				// 		this.loadMoreData(index);
				// 	});
				// },
				loadMoreData(index) {
					const group = this.grouplist[index];
					if (!group.hasMore || this.loading) return;

					this.loading = true; // 开始加载数据
					let friendData = JSON.parse(JSON.stringify(this.friendList));
					let start = (group.currentPage - 1) * this.pageSize;
					let end = group.currentPage * this.pageSize;
					let newItemsAll = friendData.filter(item => {
						if (group.group_id === 0) {
							return !item.friend_group || item.friend_group === group.group_id;
						} else {
							return item.friend_group === group.group_id;
						}
					})
					let newItems = newItemsAll.slice(start, end);
					group.data.push(...newItems);
					group.currentPage += 1;
					group.hasMore = newItems.length === this.pageSize; // 如果新加载的数据少于 pageSize，说明没有更多数据了
					this.loading = false; // 结束加载数据
					console.log(group.hasMore);
					if (!group.hasMore) {
						this.actionIndex = -1
					} else if (group.hasMore) {
						this.actionIndex = index
					}
				},
				onFriendGroupManage(data) {
					switch (data.type) {
						case 'add':
							this.grouplist.push(data.data)
							break;
						case 'edit':
							let indexedit = this.grouplist.findIndex(it => it.group_id == data.data.group_id)
							console.log(indexedit)
							if (indexedit != -1) {
								this.$set(this.grouplist[indexedit], 'group_name', data.data.group_name)
							}
							break;
						case 'del':
							let indexdel = this.grouplist.findIndex(it => it.group_id == data.data.group_id)
							if (indexdel != -1) {
								this.grouplist.splice(indexdel, 1)
							}
							break;
						default:
							break;
					}
				},
				goFriend(item) {
					this.$Router.push({
						name: 'friend_details',
						params: {
							friend_idx: item.friend_idx,
							friend_remark: item.friend_remark,
							nick_name: item.nick_name,
							avatar_url: item.avatar_url
						}
					});
				},
				manageClick() {
					this.$Router.push({
						name: 'friend_group_manage'
					});
				},
			},
		};
	</script>

	<style scoped lang="scss">
		.content {
			height: 100%;
		}

		.typetag {
			white-space: nowrap;
			font-size: 20rpx;
			color: #FFFFFF;
			padding: 0 10rpx;
			height: 28rpx;
			margin-left: 10rpx;
			line-height: 28rpx;
			text-align: center;
			border-radius: 10rpx;
			background-color: #FF7676;
		}

		.groupView {
			padding: 0 30rpx;

			.groupTop {
				.groupTopLeft {
					display: flex;
					align-items: center;

					.groupname {
						margin-left: 10rpx;
						font-size: 28rpx;
						color: #FFFFFF;
					}
				}

				.groupvalue {
					color: #61626e;
					font-size: 24rpx;
				}
			}
		}




		.listitemview {
			.listitem {
				display: flex;
				align-items: center;
				padding: 12rpx 0;
				position: relative;

				&.active {
					background-color: #1E1F30;
				}

				&::after {
					content: "";
					position: absolute;
					width: calc(100% - 140rpx);
					background-color: #1E1F30;
					height: 1rpx;
					bottom: 0;
					right: 0;
				}

				&__right {
					margin-left: 20rpx;
					flex: 1;

					&__top {
						display: flex;
						align-items: center;

						&__nickname {
							color: #fff;
							font-size: 28rpx;
						}

						&__time {
							color: #61626E;
							font-size: 20rpx;
						}
					}

					&__content {
						display: flex;
						justify-content: space-between;
						align-items: center;
						margin-top: 15rpx;

						&__msg {
							flex: 1;
							font-size: 24rpx;
							color: #595A66;
						}
					}
				}
			}
		}
	</style>